<template>
    <div>
   <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button><!-- 添加角色按钮区域 -->
        <el-table :data="rolesList" border stripe>
             <el-table-column type="expand">
                 <template slot-scope="scope">
                     <el-row v-for="(item1,index1) in scope.row.children" :key="item1.id"
                     :class="['bdbottom',index1 === 0 ? 'bdtop' : '','vcenter']">
                         <!-- 渲染一级权限 -->
                         <el-col :span="5">
                            <el-tag closable @close="removeRightByid(scope.row,item1.id)">{{item1.authName}}
                            </el-tag>
                              <i class="el-icon-caret-right"></i>
                         </el-col>
                         <!-- 渲染二级和三级权限 -->
                         <el-col :span="19">
                             <el-row v-for="(item2, index2) in item1.children" :key="item2.id"
                             :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']">  <!-- 渲染二级权限 -->
                                 <el-col :span="6" closable> <!-- 二级权限 -->
                                     <el-tag type="success" closable @close="removeRightByid(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                      <i class="el-icon-caret-right"></i>
                                 </el-col>
                                 <el-col :span="18"><!-- 三级权限 -->
                                    <el-tag  type="danger" v-for="(item3) in item2.children" :key="item3.id"
                                    closable @close="removeRightByid(scope.row,item3.id)">
                                        {{item3.authName}}
                                    </el-tag>
                                 </el-col>
                             </el-row>
                         </el-col>
                     </el-row></template></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作" width="300px">
          <template slot-scope="scope"><!-- 接受来自作用域插槽的数据 -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button><!-- 编辑按钮 -->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoles(scope.row)">删除</el-button><!-- 删除按钮 -->
          <!-- 分配角色权限按钮 -->
    <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetDialog(scope.row)">分配权限</el-button>
    </el-tooltip>
          </template>
            </el-table-column>
        </el-table>
    </el-card>
      <!-- 弹出框信息,分配权限 -->
<el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="50%" @close="closeSetDialog">
     <!-- 内容主体区域 -->
    <el-tree :data="rightsList" :props="defaultProps" show-checkbox node-key="id"
    :default-expand-all="true" :default-checked-keys="defkeys" ref="treeRef"></el-tree>
    <span slot="footer" class="dialog-footer"><!-- 底部按钮区域 -->
    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
</el-dialog>
<!-- 添加角色对话框 -->
<el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="addRoleClosed">
     <!-- 内容主体区域 -->
     <el-form :model="addRoleList" :rules="addRoleRules" ref="addRoleRef" label-width="100px">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="addRoleList.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述">
    <el-input v-model="addRoleList.roleDesc"></el-input>
  </el-form-item>
     </el-form>
    <span slot="footer" class="dialog-footer"><!-- 底部按钮区域 -->
    <el-button @click="addRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRoleTrue">确 定</el-button>
    </span>
</el-dialog>
<!-- 编辑角色对话框 -->
<el-dialog title="修改角色" :visible.sync="editRoleDialogVisible" width="50%" @close="editRoleClosed">
     <!-- 内容主体区域 -->
     <el-form :model="editRoleList" :rules="addRoleRules" ref="editRoleRef" label-width="100px">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="editRoleList.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="editRoleList.roleDesc"></el-input>
  </el-form-item>
     </el-form>
    <span slot="footer" class="dialog-footer"><!-- 底部按钮区域 -->
    <el-button @click="editRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRoleTrue">确 定</el-button>
    </span>
</el-dialog>
    </div>
</template>
<script>

export default {
  data () {
    return {
      rolesList: [], /* 所有角色列表数据 */
      rightsList: [], /* 所有列表的树形结构  */
      setRightsDialogVisible: false, // 控制分配权限对话框的现实与隐藏
      defaultProps: {
        label: 'authName',
        children: 'children'
      },
      defkeys: [], // 权限列表中默认选中的权限（某个角色拥有的权限）
      roleId: '', // 当前即将分配权限的角色ID
      addRoleDialogVisible: false, // 控制添加角色对话框的显示与隐藏
      addRoleList: { roleName: '', roleDesc: '' }, // 添加的角色的数据保存源
      // 添加角色时候的验证
      addRoleRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      editRoleList: { roleName: '', roleDesc: '', id: 0 }, // 编辑角色的数据保存源
      editRoleDialogVisible: false // 控制编辑角色对话框的代开与关闭
    }
  },
  methods: {
    async getRolesList () { // 获取角色数据列表
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色权限列表失败');
      }
      // this.$message.success('获取成功');
      this.rolesList = res.data; // 获取的数据
      // console.log(this.rolesList);
    },
    async removeRightByid (role, rightid) { // 弹窗提示用户
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除');
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`);
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败');
      }
      role.children = res.data;
      this.$message.success('删除权限成功');
      // this.getRolesList();
    },
    // 展示分配权限的对话框
    async showSetDialog (role) {
      this.roleId = role.id;
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree');
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败');
      }
      this.$message.success('获取权限成功');
      this.rightsList = res.data;
      // console.log(this.rolesList);
      this.getLeafKeys(role, this.defkeys);
      this.setRightsDialogVisible = true;
    },
    getLeafKeys (node, arr) {
      if (!node.children) { // 若不包含children属性则是三级节点
        return arr.push(node.id);
      }
      node.children.forEach(element => {
        this.getLeafKeys(element, arr)
      });
    },
    closeSetDialog () { // 监听分配权限对话框的关闭
      this.defkeys = [];
    },
    async allotRights () { // 向服务器提交修改后添加的权限
      const keys = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()];
      const idStr = keys.join(',');
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败');
      }
      this.$message.success('分配权限成功');
      this.getRolesList();
      this.setRightsDialogVisible = false;
    },
    async removeRoles (data) {
      // 删除角色
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除!');
      }
      // console.log(data);
      const { data: res } = await this.$http.delete(`roles/${data.id}`);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败!');
      }
      this.getRolesList();
      this.$message.success('删除角色成功!');
    },
    showAddRoleDialog () {
      // 展示添加角色对话框
      this.addRoleDialogVisible = true;
    },
    addRoleTrue () {
      // 添加角色（确定按钮）
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.post('roles', {
          roleName: this.addRoleList.roleName,
          roleDesc: this.addRoleList.roleDesc
        });
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败');
        }
        this.$message.success('添加角色成功');
        this.getRolesList();
        this.addRoleDialogVisible = false;
      })
    },
    addRoleClosed () {
      // 监 听添加角色对话框的关闭事件
      this.$refs.addRoleRef.resetFields();
      this.addRoleList.roleName = '';
      this.addRoleList.roleDesc = '';
    },
    showEditDialog (data) {
      // 编辑角色对话框的函数
      this.editRoleList.roleName = data.roleName;
      this.editRoleList.roleDesc = data.roleDesc;
      this.editRoleList.id = data.id;
      // console.log(this.editRoleList);
      this.editRoleDialogVisible = true;
    },
    editRoleTrue () {
      // 编辑角色信息（确定按钮）数据持久化
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.put(`roles/${this.editRoleList.id}`, {
          roleName: this.editRoleList.roleName,
          roleDesc: this.editRoleList.roleDesc
        });
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败');
        }
        this.$message.success('修改角色成功');
        this.getRolesList();
        this.editRoleDialogVisible = false;
      })
    },
    editRoleClosed () {
      // 监听编辑弹框的关闭事件
      this.$refs.editRoleRef.resetFields(); // 清空表单
      this.editRoleList.roleName = '';
      this.editRoleList.roleDesc = '';
      this.editRoleList.id = 0;
    }
  },
  created () {
    this.getRolesList()
  }

}
</script>
<style lang="less" scoped>
.el-tag{
    margin: 10px;
}
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>
